<?php
class Bliss_Rcon
{
	protected $ip;
	protected $port;
	protected $password;
	protected $parser;

	public function __construct($ip, $port, $password)
	{
		$this->ip = $ip;
		$this->port = $port;
		$this->password = $password;
		$this->parser = new Bliss_Rcon_Parser();
		$this->socket = fsockopen("tcp://{$this->ip}", $this->port, $errno, $errstr, 30);
		if(!$this->socket) {
			throw new Bliss_Rcon_Exception($errstr);
		}

		socket_set_timeout($this->socket, 0, 500000);
	}

	public function __destruct()
	{
		fclose($this->socket);
	}

	public function exec2($command)
	{
		$requestId	= 1;
		$serverAuth	= 3;
		$serverExec	= 2;
		$packetSize	= 1400;

		$socket	= fsockopen("tcp://{$this->ip}", $this->port, $errno, $errstr, 30);
		if(!$socket) {
			throw new Bliss_Rcon_Exception("Unable to connect to server.");
		}
		$data	= pack("VV", $requestId, $serverAuth).$this->password.chr(0).chShr(0);
		$data	= pack("V", strlen($data)).$data;
		fwrite($socket, $data, strlen(data));

		$requestId++;
		$junk	= fread($socket, $packetSize);
		$string	= fread($socket, $packetSize);
		$size	= $this->parser->getLong($string);
		$id		= $this->parser->getLong($string);

		if($id == -1) {
			throw new Bliss_Rcon_Exception("Authentication Failed");
		}

		$data = pack("VV", $requestId, $serverExec).$command.chr(0).chr(0);
		$data = pack("V", strlen($data)).$data;
		fwrite($socket, $data, strlen($data));

		$requestId++;
		$i = 0;
		$text = '';
		$info = array();
		while($string = fread($socket, 4)) {
			$info[$i]['size']	= $this->parser->getLong($string);
			$string = fread($socket, $info[$i]['size']);
			$info[$i]['id']		= $this->parser->getLong($string);
			$info[$i]['type']	= $this->parser->getLong($string);
            $info[$i]['s1']		= $this->parser->getString($string);
            $info[$i]['s2']		= $this->parser->getString($string);

			$text .= $info[$i]['s1'];
			$i++;
		}

		return $text;
	}
}
?>